<?php

namespace App\Admin\Actions\Audit;

use App\Library\Lock;
use App\Library\Logic\OperateLogLogic;
use App\Models\AfterSaleModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Exception;
use Illuminate\Http\Request;

class AuditAfterSaleAction extends RowAction
{
    public $name = '审核';

    /**
     * random
     * @param AfterSaleModel $model
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function handle(AfterSaleModel $model, Request $request): Response
    {
        return Lock::get($request->serialNumber . 'afterSale', function () use ($model, $request) {
            $status = AfterSaleModel::valueByWhere($model->id, null, 'status');
            if ((int)$status !== 0) return $this->response()->error('状态已经变跟,请刷新重试')->refresh();
            else if ((int)$request->status === 4) {//拒绝
                $model->status = 2;
                $model->refuse_at = now();
                $model->reply = $request->reply;
                $model->save();
                return $this->response()->success('操作成功！')->refresh();
            } else if ((int)$request->status === 2) {//指定金额
                if ((float)$request->price > (float)$model->pay_price) {
                    return $this->response()->error('退款金额不能大于' . $model->pay_price)->refresh();
                }
                $model->refund_type_id = 1;
                $model->refund_price = $request->price;
            } else if ((int)$request->status === 3) {//扣多少钱
                if ((float)$request->price > (float)$model->pay_price) {
                    return $this->response()->error('扣款金额必须小于' . $model->pay_price)->refresh();
                }
                $model->refund_type_id = 2;
                $model->refund_price = bcsub($model->pay_price, $request->price, 2);
            } else $model->refund_price = $model->pay_price;
            $model->status = 1;
            $model->agree_at = now();
            $model->reply = $request->reply;
            $model->save();
            if (!is_null($model->auctionOrder)) {
                $model->auctionOrder->status_after_sale = 2;
                $model->auctionOrder->save();
            }
            mq('afterSaleRefund', $model->serial_number);
            OperateLogLogic::add(Admin::user()->user_id, 'admin.afterSale.audit');
            return $this->response()->success('操作成功')->refresh();
        });
    }

    public function form(AfterSaleModel $model): void
    {
        $this->select('status', '审核')->options([1 => '全额退款', 2 => '指定金额', 3 => '扣多少钱', 4 => '拒绝'])->required();
        $this->text('price', '指定金额')->required()->value($model->pay_price);
        $this->text('reply', '回复');
    }
}
